package org.csu.jpetstore.web.servlet;

import org.csu.jpetstore.domain.Account;
import org.csu.jpetstore.domain.Cart;
import org.csu.jpetstore.domain.Item;
import org.csu.jpetstore.domain.Order;
import org.csu.jpetstore.service.CartService;
import org.csu.jpetstore.service.CatalogService;
import org.csu.jpetstore.service.LogService;
import org.csu.jpetstore.service.OrderService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class ViewOrderServlet extends HttpServlet {

    private CartService cartService;
    private LogService logService;
    private CatalogService catalogService;
    private OrderService orderService;
    private static final String VIEW_FINAL_ORDER = "/WEB-INF/jsp/order/FinalOrder.jsp";
    private int orderId;

//    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        doGet(request, response);
//    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        cartService = new CartService();
        logService = new LogService();
        catalogService = new CatalogService();
        orderService = new OrderService();

        HttpSession session = request.getSession();
        orderId = Integer.parseInt(request.getParameter("orderId"));
        Cart cart = new Cart();
        Account user = (Account) session.getAttribute("loginAccount");
        String username = user.getUsername();

        List<String> itemList = cartService.getOrder(orderId);
        for (int i = 0; i < itemList.size(); i++) {
            Item item = catalogService.getItem(itemList.get(i));
            int quantity = cartService.itemNum(itemList.get(i),username);
            cart.addItem(item, quantity);
        }

        Order order = orderService.getOrderById(orderId);
        order.initOrder(cart);
        Date orderDate = order.getOrderDate();
        orderDate.setTime(orderDate.getTime()-14*60*60*1000);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = df.format(orderDate);
        session.setAttribute("time", time);
        session.setAttribute("order", order);
        session.setAttribute("cart", cart);

        if(user != null) {
            Date date = new Date();
            logService.insert(user.getUsername(), date.toString(), "查看订单" + orderId);
        }


        request.getRequestDispatcher(VIEW_FINAL_ORDER).forward(request, response);

    }

}
